/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.demo.wzq.myapplication;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.google.android.cameraview.CameraView;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class CameraActivity extends AppCompatActivity {
    private CameraView mCV;
    private RelativeLayout mRlTakePhoto;
    private static final String PHOTO_CROP_PATH = "ZybAnswerPic/cropResult/";//切图结果存放位置
    private static final String PHOTO_SOURCE_PATH = "ZybAnswerPic/takePhotoResult/";//拍照之后图片存放位置
    private CameraView.Callback mCallBack = new CameraView.Callback() {
        @Override
        public void onCameraOpened(CameraView cameraView) {
            super.onCameraOpened(cameraView);
        }

        @Override
        public void onCameraClosed(CameraView cameraView) {
            super.onCameraClosed(cameraView);
        }

        @Override
        public void onPictureTaken(CameraView cameraView, final byte[] data) {
            super.onPictureTaken(cameraView, data);
            //将图片存放起来，需要新开线程
            getBackThreadHandler().post(new Runnable() {
                @Override
                public void run() {
                    File file = new File(
                            Environment.getExternalStorageDirectory(), PHOTO_SOURCE_PATH);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    mSourceFile = new File(file, "source.jpg");
                    FileOutputStream fos = null;
                    try {
                        fos = new FileOutputStream(mSourceFile);
                        fos.write(data);
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (fos != null) {
                            try {
                                fos.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    getMainHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            startCrop();
                        }
                    });
                 /*   final File picDir = new File(Environment.getExternalStorageDirectory(),
                            "ZybAnswerPic/source/");
                    picDir.mkdirs();
                    mPicFile = new File(picDir, System.currentTimeMillis() + ".jpg");
                    FileOutputStream fileOutputStream = null;
                    try {
                        fileOutputStream = new FileOutputStream(mPicFile);
                        fileOutputStream.write(data);
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (fileOutputStream != null) {
                            try {
                                fileOutputStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    CameraActivity.getMainHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inJustDecodeBounds = true;
                            BitmapFactory.decodeFile(mPicFile.getAbsolutePath(),
                                    options);
                            int height = options.outHeight;
                            options.inSampleSize = height / getResources().getDimensionPixelOffset(
                                    R.dimen.take_photo_size);
                            options.inJustDecodeBounds = false;
                            options.inPreferredConfig = Bitmap.Config.RGB_565;
                            Bitmap bitmap = BitmapFactory.decodeFile(mPicFile.getAbsolutePath(),
                                    options);
                            mIv.setImageBitmap(bitmap);
                            startCrop();
                        }
                    });*/
                }
            });
        }
    };
    private Handler mMSaveHandler;
    private ImageView mIv;
    private static Handler mHandler;
    private File mPicFile;
    private File mDesFile;
    private File mSourceFile;
    private File mCropFile;
    private View.OnClickListener mclickPicListener;

    public Handler getBackThreadHandler() {
        if (mMSaveHandler == null) {
            HandlerThread saveThread = new HandlerThread("save_pic");
            saveThread.start();
            mMSaveHandler = new Handler(saveThread.getLooper());
        }
        return mMSaveHandler;
    }

    public static Handler getMainHandler() {
        if (mHandler == null) {
            mHandler = new Handler(Looper.getMainLooper());
        }
        return mHandler;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mCV = (CameraView) this.findViewById(R.id.cv_main);
        mRlTakePhoto = (RelativeLayout) this.findViewById(R.id.bt_take_photo);
        mIv = (ImageView) this.findViewById(R.id.iv_last_pic);
        init();
    }

    private void init() {
        mSourceFile = new File(
                Environment.getExternalStorageDirectory() + "/" + PHOTO_SOURCE_PATH + "source.jpg");
        if (mSourceFile.exists()) {
            mIv.setVisibility(View.VISIBLE);
            addImgFileToIv(mIv, mSourceFile);
        } else {
            mIv.setVisibility(View.GONE);
        }
        mIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startCrop();
            }
        });

        mCV.setAdjustViewBounds(true);
        mRlTakePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCV.takePicture();
            }
        });
        mCV.addCallback(mCallBack);
    }

    private void addImgFileToIv(ImageView iv, @NonNull File sourceFile) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(sourceFile.getAbsolutePath(), options);
        options.inSampleSize = options.outHeight / getResources().getDimensionPixelOffset(
                R.dimen.take_photo_size);
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(sourceFile.getAbsolutePath(), options);
        iv.setImageBitmap(bitmap);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mCV.start();
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onPause() {
        super.onPause();
        mCV.stop();
        if (mMSaveHandler != null) {
            mMSaveHandler.getLooper().quitSafely();//4.3
        }
    }


    public void startCrop() {
        File cropDir = new File(Environment.getExternalStorageDirectory(), PHOTO_CROP_PATH);
        if (!cropDir.exists()) {
            cropDir.mkdirs();
        }
        mCropFile = new File(cropDir, "crop.jpg");
        UCrop ucrop = UCrop.of(Uri.fromFile(mSourceFile), Uri.fromFile(mCropFile));
        UCrop customUcrop = CustomUcropConfig.getAnswerUcropConfig(this, ucrop, mSourceFile);
        customUcrop.start(CameraActivity.this);
    }

    //截图结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == UCrop.REQUEST_CROP) {
            if (resultCode == RESULT_CANCELED) {//点击了X
                finish();
            }
            if (resultCode != RESULT_OK) {
                setResultError("截图失败" + data.getStringExtra(UCrop.EXTRA_ERROR));
                finish();
                return;
            }
            Uri outUri = data.getParcelableExtra(UCrop.EXTRA_OUTPUT_URI);
            float outAspect = data.getFloatExtra(UCrop.EXTRA_OUTPUT_CROP_ASPECT_RATIO, 1.0f);
            int outHeight = data.getIntExtra(UCrop.EXTRA_OUTPUT_IMAGE_HEIGHT, 0);
            int outWidth = data.getIntExtra(UCrop.EXTRA_OUTPUT_IMAGE_WIDTH, 0);
            int outOffsetX = data.getIntExtra(UCrop.EXTRA_OUTPUT_OFFSET_X, 0);
            int outOffsetY = data.getIntExtra(UCrop.EXTRA_OUTPUT_OFFSET_Y, 0);
            setResultUri(outUri, outAspect, outOffsetX, outOffsetY, outWidth, outHeight);
            finish();
        }
    }

    protected void setResultUri(Uri uri, float resultAspectRatio, int offsetX, int offsetY,
            int imageWidth, int imageHeight) {
        setResult(RESULT_OK, new Intent()
                .putExtra(UCrop.EXTRA_OUTPUT_URI, uri)
                .putExtra(UCrop.EXTRA_OUTPUT_CROP_ASPECT_RATIO, resultAspectRatio)
                .putExtra(UCrop.EXTRA_OUTPUT_IMAGE_WIDTH, imageWidth)
                .putExtra(UCrop.EXTRA_OUTPUT_IMAGE_HEIGHT, imageHeight)
                .putExtra(UCrop.EXTRA_OUTPUT_OFFSET_X, offsetX)
                .putExtra(UCrop.EXTRA_OUTPUT_OFFSET_Y, offsetY)
        );
    }

    protected void setResultError(String throwable) {
        setResult(UCrop.RESULT_ERROR, new Intent().putExtra(UCrop.EXTRA_ERROR, throwable));
    }
}
